<?php
header('Content-Type: application/json; charset=utf-8');

/* 1. 数据库连接 */
$dbConfig = include('db_config.php');
try {
    $dsn = "mysql:host={$dbConfig['host']};dbname={$dbConfig['dbname']};charset={$dbConfig['charset']}";
    $pdo = new PDO($dsn, $dbConfig['username'], $dbConfig['password']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => '数据库连接失败：' . $e->getMessage()], JSON_UNESCAPED_UNICODE);
    exit;
}

/* 2. 取 id */
$id = $_POST['id'] ?? null;
if ($id === null || $id === '') {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => '缺少参数 id'], JSON_UNESCAPED_UNICODE);
    exit;
}

/* 3. 字段列表（和表结构一致） */
$fields = [
    '上传者用户的id',
    '文件标题',
    '文件介绍',
    '文件大小',
    '文件格式',
    '获赞数量',
    '文件链接',
    '文件封面',
    '文件图标',
    '文件备注',
    '上传时间',
    '是否已审核',
    '审核者的用户id',
    '拒绝原因'
];

/* 4. 过滤出需要更新的字段 */
$setParts = [];
$bind = [':id' => $id];

foreach ($fields as $f) {
    if (isset($_POST[$f]) && $_POST[$f] !== '') {
        // 给每个字段起安全的占位符名：col_0, col_1 ...
        $key = ':col_' . count($setParts);
        $setParts[] = "`$f` = $key";
        $bind[$key] = $_POST[$f];
    }
}

if (!$setParts) {
    http_response_code(400);
    echo json_encode(['status' => 'error', 'message' => '没有任何需要更新的字段'], JSON_UNESCAPED_UNICODE);
    exit;
}

/* 5. 拼接并执行 SQL */
$sql = "UPDATE `mi_file` SET " . implode(', ', $setParts) . " WHERE `id` = :id";

try {
    $stmt = $pdo->prepare($sql);
    $stmt->execute($bind);

    echo json_encode([
        'status'  => 'success',
        'message' => '更新成功',
        'updated' => $stmt->rowCount()
    ], JSON_UNESCAPED_UNICODE);
} catch (PDOException $e) {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => '更新失败：' . $e->getMessage()], JSON_UNESCAPED_UNICODE);
}
?>